import { API_BASE_URL } from '@/config/apiConfig';
import { getToken } from './auth';

// 添加一个函数来验证字符串是否为有效的 Base64 编码
function isValidBase64(str) {
  try {
    return btoa(atob(str)) === str;
  } catch (err) {
    return false;
  }
}

// 封装带token的request方法
export const request = (options) => {
  return new Promise((resolve, reject) => {
    const makeRequest = () => {
      const token = getToken();
      const authorizationHeader = isValidBase64(token) ? `Bearer ${token}` : '';
      
      uni.request({
        url: `${API_BASE_URL}${options.url}`,
        method: options.method || 'GET',
        data: options.data || {},
        header: {
          'Authorization': authorizationHeader,
          'Token': token,
          ...options.header
        },
        success: (res) => {
          if (res.statusCode === 401) {
            refreshToken().then(() => {
              makeRequest();
            }).catch(() => {
              uni.navigateTo({
                url: '/pages/login/login'
              });
            });
            return;
          }
          // 调用传入的success回调
          if (options.success) {
            options.success(res);
          }
          resolve(res.data);
        },
        fail: (err) => {
          // 调用传入的fail回调
          if (options.fail) {
            options.fail(err);
          }
          reject(err);
        }
      });
    };

    makeRequest();
  });
};

// 添加刷新token的方法
const refreshToken = () => {
  return new Promise((resolve, reject) => {
    // 这里调用您的刷新token接口
    uni.request({
      url: `${API_BASE_URL}/auth/refresh`,
      method: 'POST',
      success: (res) => {
        if (res.statusCode === 200) {
          // 保存新token
          setToken(res.data.token);
          resolve();
        } else {
          reject();
        }
      },
      fail: (err) => {
        reject(err);
      }
    });
  });
};
